package com.waimai1.waimai.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.waimai1.waimai.common.Utils;
import com.waimai1.waimai.entity.MyOrder;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.FlService;
import com.waimai1.waimai.service.MyOrderService;
import com.waimai1.waimai.service.WepayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class FlServiceImpl implements FlService {
    @Autowired
    private MyOrderService myOrderService;
    @Autowired
    private WepayService wepayService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Object getData(Map<String, Object> bizMap, String method) {
        Map<String, String> signMap = new HashMap<>();
        Date time = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeFormat = sdf.format(time);

        signMap.put("app_key", Utils.FLAppkey);
        signMap.put("method", method);
        signMap.put("timestamp", timeFormat);
        signMap.put("version", "2.0");
        signMap.put("format", "json");
        signMap.put("charset", "utf-8");
        signMap.put("sign_type", "md5");
        signMap.put("app_auth_token", "");
        signMap.put("biz_content", JSON.toJSONString(bizMap));
        String sign = Utils.getFlSign(signMap, bizMap);
        signMap.put("sign", sign);
//     http接口调用web
        WebClient webClient = WebClient.builder()
                .defaultHeader("Content-Type", "application/json")
                .baseUrl("http://openapi.fulu.com/api/getway")
//                .baseUrl("http://pre.openapi.fulu.com/api/getway")//沙箱环境
                .codecs(obj -> obj.defaultCodecs().maxInMemorySize(10 * 1024 * 1024)).build();
        Mono<Object> result = webClient.post()
                .body(BodyInserters.fromValue(signMap))//json传递
                .retrieve()
                .bodyToMono(Object.class);
        Object resObj = result.block();
        return resObj;
    }

    //创建福禄平台实际订单
    @Override
    public void createFLOrder(MyOrder order) {
        Map<String, Object> bizMap = new HashMap<String, Object>();
        bizMap.put("customer_order_no", order.getOutTradeNo());
        String method = "";
        switch (order.getCinemaName()) {
            case "话费充值":
                method = "fulu.order.mobile.add";
                JSONObject receiveInfoJson = JSON.parseObject(order.getReceiveInfo());
                bizMap.put("charge_phone", receiveInfoJson.get("charge_phone"));
                bizMap.put("charge_value", order.getTotalPrice());  //充值金额为拉起支付的金额
//                bizMap.put("charge_value", 100); //TODO 测试用值
                break;
            case "福禄产品直充":
                method = "fulu.order.direct.add";
                JSONObject params = JSON.parseObject(order.getSeat());
                bizMap.putAll(params);
                break;
            case "福禄产品卡密":
                method = "fulu.order.card.add";
                params = JSON.parseObject(order.getSeat());
                bizMap.putAll(params);
                break;
            default:
                throw new NotErrorException(1007, "未匹配到对应订单类型");
        }
        log.info("argsMap:{}", bizMap.toString());
        Map<String, Object> res = (Map<String, Object>) getData(bizMap, method);
        System.out.println("================================================================");
        System.out.println(res);
        System.out.println("================================================================");

        if (!"0".equals(res.get("code").toString())) {
            order.setHwStatus("下单失败");
            //自动退款，不在人工审核
            wepayService.allRefund(order);
            order.setStatus(Utils.STATUS_REFUNDED);
            //保存失败原因
            JSONObject refundInfoJson = new JSONObject();
            refundInfoJson.put("refundReason", (String) res.get("message"));//设置待退款商品信息
            order.setRefundInfo(refundInfoJson.toJSONString());
            myOrderService.updateById(order);
            throw new NotErrorException(1008, res.get("code") + (String) res.get("message"));
        } else {
//            现加定时查单
            redisTemplate.opsForSet().add("FlOrderSearch", order.getOutTradeNo());
            order.setHwStatus("下单成功");
            JSONObject parsedObject = JSON.parseObject((String) res.get("result"));
            order.setHwOrderId(parsedObject.get("order_id").toString());
            myOrderService.updateById(order);
        }
    }
    @Override
    public List<Map> getArrayData(Map<String, Object> map) {
        String method = map.get("method").toString();
        map.remove("method");
        Map<String, Object> res = (Map<String, Object>) getData(map, method);

        System.out.println("================================================================");
        System.out.println(res);
        System.out.println("================================================================");

        if (!"0".equals(res.get("code").toString())) {
            throw new NotErrorException(1008, res.get("code") + (String) res.get("message"));
        }
        String result = (String) res.get("result");
        List<Map> maps = JSON.parseArray(result, Map.class);
        return maps;
    }

}
